package cn.eports.learn.web.servlet;

import cn.eports.learn.domain.User;
import cn.eports.learn.service.UserService;
import cn.eports.learn.service.impl.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/addUserServlet")
public class AddUserServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        super.doPost(req, resp);
        //1. 设置编码
        req.setCharacterEncoding("utf-8");

        //2. 获取参数
        final Map<String, String[]> map = req.getParameterMap();
        //3. 封装User对象
        User user = new User();
        try{
            BeanUtils.populate(user, map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        //4. 调用service保存
        UserService service = new UserServiceImpl();
        service.addUser(user);

        //5. 跳转到userListServlet
        resp.sendRedirect(req.getContextPath() + "/userListServlet");
    }
}
